<?php
class Authorise
{
	var $m_login;
	var $m_pass;
	var $m_remember;
	var $m_sessionName;
	var $m_userTable;
	var $m_dbloginField;
	var $m_dbPassField;
	var $m_extraFilter;
	var $m_idField;
	var $m_loginError;
	var $m_write2Session;

	function Authorise($userTable,$extraFilter,$idField='id',$loginFld='login',$passFld='pass',$sessionName='valid_user',$writeToSessionFlds=false,$loginInput='login',$passInput='pass',$rememberInput='rememberme')
	{

		
		$this->m_userTable=$userTable;
		$this->m_dbloginField=$loginFld;
		$this->m_dbPassField=$passFld;
		$this->m_sessionName=$sessionName;
		$this->m_idField=$idField;
		if ($writeToSessionFlds)
		{
		$this->m_write2Session=','.$writeToSessionFlds;
		}

		if (is_array($extraFilter))
		{
			foreach ($extraFilter as $k=>$v)
			{
				$this->m_extraFilter="and $k='$v'";
			}
		}
		
		if (!$_COOKIE[$this->m_dbloginField])
		{
			$this->m_login=trim($_POST[$loginInput]);
			$this->m_pass=trim($_POST[$passInput]);
			$this->m_remember=$rememberInput;
			
		}
		else
		{
			$this->m_login=$_COOKIE[$loginFld];
			$this->m_pass=$_COOKIE[$passFld];
		}
	}


	function Login()
	{
		if ($this->m_login && $this->m_pass && !$_SESSION[$this->m_sessionName])
		{
			
			$table = new CARXTable($this->m_userTable,"$this->m_dbloginField='$this->m_login' $this->m_extraFilter","$this->m_dbloginField,$this->m_dbPassField,$this->m_idField".$this->m_write2Session);
			$data = $table->FetchRow();
		
			if ($data[$this->m_dbPassField]==$this->m_pass)
			{
				$_SESSION[$this->m_sessionName]=$data[$this->m_idField];
				if ($this->m_write2Session)
				{
					$writeToSession=explode(",",$this->m_write2Session);
					foreach ($writeToSession as $k=>$v)
					{
						$_SESSION[$v]=$data[$v];
					}
				}
				if ($_POST['rememberme'])
				{
					setcookie($this->m_dbloginField,$data[$this->m_dbloginField],time()+86400);
					setcookie($this->m_dbPassField,$data[$this->m_dbPassField],time()+86400);
				}
		
				header("Location:".str_replace("?logout=1","",$_SERVER['REQUEST_URI'])."");
				return 1;
			}

			else
			{
				$this->m_loginError=true;
				return 0;
			}
		}
	}

	function LogOut()
	{
		unset($_SESSION[$this->m_sessionName]);
		setcookie($this->m_dbloginField,'',time()+86400);
		setcookie($this->m_dbPassField,'',time()+86400);
		header("Location:".str_replace("?logout=1","",$_SERVER['REQUEST_URI'])."");
		
	}
}

?>